package cn.fz.luck.saas.config.security;

import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;

/**
 * 授权:访问决策器
 * Created by zhuangqi on 17-7-6.
 */
@Service
public class CustomAccessDecisionManager implements AccessDecisionManager {

    @Override
    public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {

        HttpServletRequest request = ((FilterInvocation) object).getHttpRequest();
        if (configAttributes == null) {
            //没定义则无权限
            throw new AccessDeniedException("Access Dendied");
        }
        //所请求的资源需要的权限
        for (ConfigAttribute configAttribute : configAttributes) {
            //访问所请求资源所需要的权限
            String needPermission = configAttribute.getAttribute();
            String needUrl = needPermission.substring(0,needPermission.indexOf(":"));
            String needMethod = needPermission.substring(needPermission.indexOf(":")+1);
            System.out.println("needPermission is " + needPermission);
            //用户所拥有的权限authentication
            for (GrantedAuthority ga : authentication.getAuthorities()) {
                if (ga instanceof CustomGrantedAuthority) {
                    CustomGrantedAuthority urlGrantedAuthority = (CustomGrantedAuthority) ga;
                    AntPathRequestMatcher matcher = new AntPathRequestMatcher(needUrl);
                    if (matcher.matches(request)){
                        if (needMethod.equals(urlGrantedAuthority.getMethod())) {
                            return;
                        }
                    }
                }
            }
        }
        //没有权限
        throw new AccessDeniedException("Access Dendied");
    }

    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
